package com.lingo.dingrobotutils.model.msgBuilder;

import com.dingtalk.api.request.OapiRobotSendRequest;
import com.lingo.dingrobotutils.model.component.DingButton;
import com.lingo.dingrobotutils.model.component.DingButtonOrientation;

import java.util.ArrayList;
import java.util.List;

/**
 * @file: com.lingo.dingRobot.common.model.msgBuilder.DingActionCardMsgBuilder
 * @Description: 封装 ActionCard 钉钉消息类型
 * @author: lingo
 * @version: v1.0
 * @date: 2020/3/23 9:37
 * @Company: www.xyb2b.com
 */

public class DingActionCardMsgBuilder extends MyDingMsgBuilder {

    private final OapiRobotSendRequest.Actioncard actionCard = new OapiRobotSendRequest.Actioncard();

    public DingActionCardMsgBuilder() {
        this.request.setMsgtype("actionCard");
        this.request.setActionCard(actionCard);
    }

    public DingActionCardMsgBuilder setTitle(String title){
        if (title != null && !title.isEmpty()){
            this.actionCard.setTitle(title);
        }
        return this;
    }

    public DingActionCardMsgBuilder setContent(String markDownContent){
        if (markDownContent != null && !markDownContent.isEmpty()){
            this.actionCard.setText(markDownContent);
        }
        return this;
    }


    public DingActionCardMsgBuilder setBtnOrientation(DingButtonOrientation orientation){
        this.actionCard.setBtnOrientation(orientation.getCode()+"");
        return this;
    }

    public DingActionCardMsgBuilder setHideAvatar(boolean isHideAvatar){
        this.actionCard.setHideAvatar(isHideAvatar ? "1" : "0");
        return this;
    }

    /**
     * 如果设置了 singleBtn 则 setBtns 会无效
     * @param btns
     * @return
     */
     public DingActionCardMsgBuilder setBtns(List<DingButton> btns){
        if (btns!=null && !btns.isEmpty()){
            if (btns.size() == 1) {
                return setSingleBtn(btns.get(0));
            }
            List<OapiRobotSendRequest.Btns> toBtns = new ArrayList<>(btns.size());
            btns.forEach(btn ->{
                OapiRobotSendRequest.Btns tempBtn = new OapiRobotSendRequest.Btns();
                tempBtn.setActionURL(btn.getUrl());
                tempBtn.setTitle(btn.getTitle());
                toBtns.add(tempBtn);
            });
            this.actionCard.setBtns(toBtns);
        }
        return this;
    }

    private DingActionCardMsgBuilder setSingleBtn(DingButton btn){
        if (btn != null){
            this.actionCard.setSingleTitle(btn.getTitle());
            this.actionCard.setSingleURL(btn.getUrl());
        }
        return this;
    }

    @Override
    public OapiRobotSendRequest build() {
        this.request.setActionCard(actionCard);
        return request;
    }
}
